package com.ruoyi.web.utils;

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

@Data
@Component
@ConfigurationProperties(prefix = "spring.mail")
public class EmailSender {

    //SMTP服务器地址
    private static String host;
    //端口号
    private static String port;
    //发件人邮箱
    private static String userName;
    //授权码
    private static String passWord;

    //收件人邮箱
    public static void send(String recipient){

        //邮件内容
        String subject = "测试邮件";
        String body = "这是一封测试邮件，来自Java程序";

        //设置邮件服务器的配置
        Properties properties = new Properties();
        properties.put("mail.smtp.host",host);
        properties.put("mail.smtp.port",port);
        properties.put("mail.smtp.auth","true");
        properties.put("mail.smtp.starttls","true");

        //创建session会话对象
        Session session = Session.getInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(userName,passWord);
            }
        });

        try {
            //创建邮件对象
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(userName));
            message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(recipient));
            message.setSubject(subject);
            message.setText(body);

            //发送邮件
            Transport.send(message);
        }catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }
}
